using Services;
using Skills;
using System.Collections.Generic;
using UnityEngine;
using XNode;

public class SkillTreeManager : MonoBehaviour
{
    [SerializeField]
    private NodeGraph graph;
    public NodeGraph Graph { get { return graph; } }
    private Player player;
    public int SkillPoint => player.SkillPoint;

    private void Start()
    {
        player = ServiceLocator.Get<ActionController>().player;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
            MyReset();
    }

    public bool TryLearnSkill(SkillNode node)
    {
        if (!node.Learned && node.Unlock && player.SkillPoint >= node.cost_sp)
        {
            node.Learned = true;
            player.SkillPoint -= node.cost_sp;
            player.SkillManager.LearnSkill(node.m_skill);
            return true;
        }
        return false;
    }

    public void MyReset()
    {
        List<Skill> skills = new List<Skill>();
        List<RuntimeSkill> runtimeSkills = player.SkillManager.GetAllSkills();
        foreach (RuntimeSkill runtimeSkill in runtimeSkills)
        {
            skills.Add(runtimeSkill.SkillAttached);
        }
        MyReset(skills);
    }

    public void MyReset(List<Skill> skills)
    {
        Dictionary<Skill, SkillNode> dict_node = new Dictionary<Skill, SkillNode>();
        List<SkillNode> nodes = new List<SkillNode>();
        foreach (Node node in graph.nodes)
        {
            nodes.Add(node as SkillNode);
        }
        foreach (SkillNode node in nodes)
        {
            node.Learned = false;
            dict_node.Add(node.m_skill, node);
        }
        foreach (Skill skill in skills)
        {
            dict_node.TryGetValue(skill, out SkillNode node);
            if (node != null)
                node.Learned = true;
        }
        foreach (SkillNode node in nodes)
        {
            node.Input();
        }
    }

    public SkillNode FindNode(Skill skill)
    {
        foreach (SkillNode node in graph.nodes)
        {
            if (node.m_skill == skill)
                return node;
        }
        return null;
    }
}
